package com.crm.common.util;

import com.alibaba.excel.util.CollectionUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author:chaifuyou
 * @Date: 2021/4/19 8:12
 */
public class YearWeeksUtil {

    public static void main(String[] args) {
        System.out.println(getMonthEnd(2021,03));
    }
    public static void main2(String[] args) {
        LocalDate localDate = LocalDate.now();
        localDate = localDate.minusMonths(3);
        Date date=new Date();
        SimpleDateFormat f =new  SimpleDateFormat("yyyy");
        String time=f.format(date);
        int year = Integer.parseInt(time);
        Map<String, Map<String, String>> yearWeekMap = YearWeeksUtil.getYearWeekMap(year);
        if (Objects.nonNull(yearWeekMap)){
            f =new  SimpleDateFormat("yyyyMMdd");
            time=f.format(date);
            for (int i=yearWeekMap.size();i > 0;i--){
                Map<String, String> map= yearWeekMap.get(""+i+"");
                for(String key:map.keySet()){
                    LinkedHashMap linkedHashMap= new LinkedHashMap();
                    //System.out.println("key:"+key+" "+"Value:"+yearWeekMap.get(key));
                    //System.out.println("key:"+key+" "+"Value:"+map.get(key));
                    String valueDate = map.get(key).replaceAll("-","").substring(0,8);
                    if (Integer.valueOf(valueDate) >= Integer.valueOf(time)){
                        if ((Integer.valueOf(valueDate) - Integer.valueOf(time)) < 7){
                            test(i,yearWeekMap);
                            break;
                            /*for (int k=1;k < 13;k++){
                                Map<String,String> weekDateMap =yearWeekMap.get(""+(i-1)+"");
                                for(String weekKey:weekDateMap.keySet()){
                                    System.out.println("key:"+weekKey+" "+"Value:"+weekDateMap.get(weekKey));
                                    break;
                                }
                            }*/
                        }
                    }
                }

            }
            /*for(String key:map.keySet()){
                boolean bo =true;
                System.out.println("key:"+key+" "+"Value:"+map.get(key));
                String valueDate = map.get(key).replaceAll("-","").substring(0,8);
                if (Integer.valueOf(valueDate) >= Integer.valueOf(time)){
                    if ((Integer.valueOf(valueDate) - Integer.valueOf(time)) < 7){
                        for (int i=0;i < 13;i++){
                            yearWeekMap.get(""++"");
                        }
                    }
                }
            }*/
        }
    }

    /**
     * 获取当前日期的近三个月的周的开始和结束日期
     * @Author chaifuyou
     * @return
     */
    public static List<String> getThisDateThreeWeek(){
        List<String> list=new ArrayList<>();
        String weekend;
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //三个月前的今天
        LocalDate localDate=LocalDate.now().minusMonths(3);
        Integer week = getWeek(localDate.toString());
        if (week > 1){
            week = week -1;
            localDate = localDate.minusDays(week);
        }
        for (int i =1;i<14;i++){
            String date;
            if (i == 1){
                date = localDate.toString();
                weekend = localDate.plusDays(6).toString();
            }else {
                //Integer day = (i - 1) * 7;
                date = localDate.plusDays(7).toString();
                weekend =LocalDate.parse(date, fmt).plusDays(6).toString();
            }
            localDate = LocalDate.parse(date, fmt);
            date = date+" 至 "+weekend;
            list.add(date);
        }
        return list;
    }

    public static void test(int i,Map<String, Map<String, String>> yearWeekMap){
        System.out.println("11111----1111");
        for (int k=1;k < 13;k++){
            Map<String, String> map = new HashMap<>();
            if (k ==1 ){
                map = yearWeekMap.get(""+i+"");
            }else {
                i = i-1;
                map = yearWeekMap.get(""+(i)+"");
            }
            for(String key:map.keySet()){
                System.out.println("key:"+key+" "+"Value:"+map.get(key));
                break;
            }
        }

    }

    /**
     * 根据日期判断周几
     * @Author chaifuyou
     * @return
     */
    public static Integer getWeek(String dates){
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Date d=null;
        try {
            d=f.parse(dates);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        cal.setTime(d);
        int w=cal.get(Calendar.DAY_OF_WEEK)-1;
        if(w==0) w=7;
        return w;
    }

    public static Map<String, Map<String, String>> sortMapByValues(Map<String, Map<String, String>> aMap) {
        Map<String, Map<String, String>> finalOut = new LinkedHashMap<>();
        aMap.entrySet()
                .stream()
                .sorted((p1, p2) -> p2.getKey().compareTo(p1.getKey()))
                .collect(Collectors.toList()).forEach(ele -> finalOut.put(ele.getKey(), ele.getValue()));
        return finalOut;
    }



    /**
     * 获取当前年
     * @return
     */
    public static String getCurrentYear() {
        Calendar calendar = Calendar.getInstance();
        int weekYear = calendar.get(Calendar.YEAR);//获得当前的年
        return weekYear+"";
    }

    /**
     * 获取当前月
     * @return
     */
    public static String getCurrentMonth() {
        Calendar calendar = Calendar.getInstance();
        int weekYear = calendar.get(Calendar.MONTH);//获得当前的月
        return weekYear+"";
    }

    /**
     * 获取今天
     * @return String
     * */
    public static String getToday(){
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }
    /**
     * 获取昨天
     * @return String
     * */
    public static String getYestoday(){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,-1);
        Date time=cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }
    /**
     * 获取本月开始日期
     * @return String
     * **/
    public static String getMonthStart(){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date time=cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00";
    }
    /**
     * 获取某年某月开始日期
     * @return String
     * **/
    public static String getMonthStart(int year,int month){
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date time=cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00";
    }
    /**
     * 获取本月最后一天
     * @return String
     * **/
    public static String getMonthEnd(){
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date time=cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 23:59:59";
    }

    /**
     * 获取某年某月最后一天
     * @return String
     * **/
    public static String getMonthEnd(int year,int month){
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date time=cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }
    /**
     * 获取本周的第一天
     * @return String
     * **/
    public static String getWeekStart(){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.WEEK_OF_MONTH, 0);
        cal.set(Calendar.DAY_OF_WEEK, 2);
        Date time=cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00";
    }
    /**
     * 获取本周的最后一天
     * @return String
     * **/
    public static String getWeekEnd(){
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));
        cal.add(Calendar.DAY_OF_WEEK, 1);
        Date time=cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time)+" 23:59:59";
    }
    /**
     * 获取本年的第一天
     * @return String
     * **/
    public static String getYearStart(){
        return new SimpleDateFormat("yyyy").format(new Date())+"-01-01 00:00:00";
    }

    /**
     * 获取某年的第一天
     * @return String
     * **/
    public static String getYearStart(int year){
        return year+"-01-01 00:00:00";
    }

    /**
     * 获取本年的最后一天
     * @return String
     * **/
    public static String getYearEnd(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH,calendar.getActualMaximum(Calendar.MONTH));
        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date currYearLast = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(currYearLast)+" 23:59:59";
    }

    /**
     * 获取某年的最后一天
     * @return String
     * **/
    public static String getYearEnd(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,calendar.getActualMaximum(Calendar.MONTH));
        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date currYearLast = calendar.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(currYearLast)+" 23:59:59";
    }

    /**
     * 获取某年某周的时间跨度
     * @param year
     * @param week
     * @return
     */
    public static Map<String, String> getWeekRangeMap(int year, int week) {
        Map<String, String> timeMap = new HashMap<String, String>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,year);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周开始的第一天
        calendar.setMinimalDaysInFirstWeek(4);//可以不用设置
        int weekYear = calendar.get(Calendar.YEAR);//获得当前的年
        calendar.setWeekDate(weekYear, week, 2);//获得指定年的第几周的开始日期
        Date time=calendar.getTime();
        String startTime = new SimpleDateFormat("yyyy-MM-dd").format(time)+" 00:00:00";
        timeMap.put("startTime",startTime);
        calendar.setWeekDate(weekYear, week, 1);//获得指定年的第几周的结束日期
        time=calendar.getTime();
        String endTime = new SimpleDateFormat("yyyy-MM-dd").format(time)+" 23:59:59";
        timeMap.put("endTime",endTime);
        return timeMap;
    }

    /**
     * 获取某年有多少周
     * @param year
     * @return
     * @throws
     */
    public static int getYearWeekConut(int year){
        int week = 52;
        try {
            /*Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周开始的第一天
            calendar.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
            week = calendar.get(Calendar.WEEK_OF_YEAR);*/
            Map<String, String> timeMap = getWeekRangeMap(year,53);
            if(!CollectionUtils.isEmpty(timeMap)){
                String startTime = timeMap.get("startTime");
                if(startTime.substring(0, 4).equals(year+"")){ //判断年度是否相符，如果相符说明有53个周。
                    week = 53;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return week;
    }

    /**
     * 获取某年所有周的时间跨度
     * @param year
     * @return
     */
    public static Map<String, Map<String, String>> getYearWeekMap(int year) {
        int weeks = getYearWeekConut(year);
        Map<String, Map<String, String>> yearWeekMap = new HashMap<String, Map<String, String>>();
        for (int i =1;i<=weeks;i++){
            Map<String, String> timeMap = getWeekRangeMap(year,i);
            yearWeekMap.put(i+"",timeMap);
        }
        return yearWeekMap;
    }

    /**
     * 获取某年某月有多少天
     * @param year
     * @param month
     * @return
     */
    public static int getDayOfMonth(int year, int month){
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0); //输入类型为int类型
        return c.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 把一段时间分成周
     * @param begins 开始日期
     * @param ends 结束日期
     * @return {@link {java.util.List<java.lang.String>}}
     */
    public static List<String> getWeeks(String begins, String ends) throws Exception {
        List<String> listWeekOrMonth = new ArrayList<String>();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdw = new SimpleDateFormat("u");
        String begiDate = begins;
        String endDate = ends;
        String beginDateFm = begins;
        String endDateFm = ends;
        Date b = null;
        Date e = null;
        b = sd.parse(beginDateFm);
        e = sd.parse(endDateFm);
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(b);
        Date time = b;
        String year = beginDateFm.split("-")[0];
        String mon = Integer.parseInt(beginDateFm.split("-")[1]) < 10 ? beginDateFm.split("-")[1] : beginDateFm.split("-")[1];
        String day = Integer.parseInt(beginDateFm.split("-")[2]) < 10 ? beginDateFm.split("-")[2] : beginDateFm.split("-")[2];
        String timeb = year + mon + day;
        String timee = null;
        if (begiDate == endDate) {
            listWeekOrMonth.add(begiDate + " 至 " + endDate);
        } else {
            while (time.getTime() <= e.getTime()) {
                time = sd.parse(sd.format(rightNow.getTime()));
                if (time.getTime() > e.getTime()) {
                    break;
                }
                String timew = sdw.format(time);
                if (("1").equals(timew)) {
                    timeb = (sd.format(time)).replaceAll("-", "");
                }
                if (("7").equals(timew) || time.getTime() == e.getTime()) {
                    timee = (sd.format(time)).replaceAll("-", "");
                    String begindate = formatToDatas(timeb);
                    String enddate = formatToDatas(timee);
                    listWeekOrMonth.add(begindate + " 至 " + enddate);
                }
                rightNow.add(Calendar.DAY_OF_YEAR, 1);
            }
        }
        return listWeekOrMonth;
    }

    /**
     * 格式化日期
     * @param data 日期
     * @return {@link {java.lang.String}}
     */
    private static String formatToDatas(String data) {
        DateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        try {
            Date parse = fmt.parse(data);
            DateFormat fmt2 = new SimpleDateFormat("yyyy-MM-dd");
            return fmt2.format(parse);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}
